<?php
/**
 * User: YL
 * Date: 2019/09/12
 */

namespace App\Middleware;

use Closure;
use Illuminate\Http\Request;
use restful\utils\Cipher;

class ParamsHandler
{
    /**
     * 过滤键
     * @var array
     */
    protected $filter = ['sign', 'nonce', 'timestamp', 'file', 'where'];

    /**
     * Handle an incoming request.
     *
     * @param  Request  $request
     * @param  Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // 是否直接存在json格式的params参数（Android）
        $isJson = json_decode($request->input('params', ''), true);

        // 请求参数
        $params = $isJson ?? $request->all();

        // 请求解密
        if ($request->exists('params') && ! $isJson) {
            $params = Cipher::request($request, $request->input('params'));
        }

        // 过滤
        $request->params = array_filter($params, function ($k) {
            return ! in_array($k, $this->filter);
        }, ARRAY_FILTER_USE_KEY);

        // 转换格式
        $request->params = $this->transform($request->params);

        return $next($request);
    }

    /**
     * 转换格式
     * @param array $params
     * @return mixed
     */
    protected function transform(array $params)
    {
        return filter_var($params, FILTER_CALLBACK, ['options' => function ($v) {
            $v = trim($v);
            return $v === '' ? null : $v;
        }]);
    }
}
